/**
 * 
 */
package cn.gov.msa.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.ctc.wstx.util.WordResolver;

import cn.gov.msa.service.WorkFlowService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author Administrator
 *
 */

//@RestController
@RestController@RequestMapping(value = "/deploy", produces="text/plain;charset=UTF-8")
public class WorkFlowController {
	String projectPath = System.getProperty("user.dir");
	String bpmPath = projectPath + "/src/main/webapp/backstage/declareflow/deploy/bpmn"; 
	
	
	@Autowired
	private WorkFlowService workFlowService;

	@RequestMapping(value = "/list")
	public @ResponseBody String list(@RequestBody JSONObject params) throws Exception {
		String result = "";
				
		List<Deployment> deploymentList = workFlowService.getWorkFlowDeployList();
        
		JSONArray ja = new JSONArray();
		for (Deployment deployment : deploymentList) {
		
			JSONObject json = new JSONObject();
			json.put("deployId", deployment.getId());
			json.put("deployName", deployment.getName());

	        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
			String str = sdf.format(deployment.getDeploymentTime());
			json.put("deployTime", str);

			List<ProcessDefinition> processDefinitionList = workFlowService.getWorkDefinitionListByDeploymentId(deployment.getId());
			if(processDefinitionList.size() > 0){
				json.put("key", processDefinitionList.get(0).getKey());
				json.put("version", processDefinitionList.get(0).getVersion());				
			}
			

			ja.add(json);
		}		
		
		
		JSONObject jsonResult = new JSONObject();
		jsonResult.put("total", deploymentList.size());
		jsonResult.put("rows", ja);
		
		
		result = jsonResult.toString();

		return result;
	}
    
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file, String deployName) throws Exception {        

		int result = 0;
		String info = "删除失败！";
		
		JSONObject jsonResult = new JSONObject();
		

        try {
            CommonsMultipartFile cf = (CommonsMultipartFile)file;   
            //这个myfile是MultipartFile的  
            DiskFileItem fi = (DiskFileItem) cf.getFileItem();  
            File targetFile = fi.getStoreLocation();  
	
//	        String deployName = "一级审批流程（无监督检查）";
	        
	        //acititi部署
	        String deploymentId =  workFlowService.deployWithZip(targetFile, deployName);
	        
	        if(deploymentId != ""){
				result = 1;
				info = "流程部署成功！";		
	        }
	        else{
				result = 0;
				info = "流程部署失败！";		
	        }                 
        } catch (Exception e) {
            e.printStackTrace();

			result = 2;
			info = "流程部署异常！";		
        }

		jsonResult.put("result", result);
		jsonResult.put("info", info);
		
        return jsonResult.toString();
    }

    
	@RequestMapping(value = "/delete")
	public @ResponseBody String delete(String deploymentId) throws Exception {
		int result = 0;
		String info = "删除失败！";
		
		JSONObject jsonResult = new JSONObject();
		
		boolean b = false;
		try{
			b = workFlowService.deleteDeploy(deploymentId);
			
			if(b){
				result = 1;
				info = "删除成功！";			
			}
			else{
				result = 0;
				info = "删除失败！";		
			}
		}
		catch(Exception e){
			e.printStackTrace();
			result = 2;
			info = "删除异常！";		
		}
		
		jsonResult.put("result", result);
		jsonResult.put("info", info);
		
		return jsonResult.toString();
	}
	

	@RequestMapping(value = "/showFlowImage")
	public @ResponseBody String  showFlowImage(HttpServletRequest request,HttpServletResponse response, String deploymentId, String taskId) throws Exception{
		
        response.setContentType("image/png");  
        response.setCharacterEncoding("utf-8");  
        try {
        	if(taskId != null && deploymentId == null){
        		deploymentId = workFlowService.getDeploymentIdByTaskId(taskId); 
        	}
        	
			if(deploymentId != null) {
				OutputStream outputStream=response.getOutputStream();  
				InputStream in = workFlowService.showFlowImage(deploymentId, "");  
				int len=0;  
				byte[]buf=new byte[1024];  
				while((len=in.read(buf,0,1024))!=-1){  
					outputStream.write(buf, 0, len);  
				}
				
				outputStream.close();  
			}
        } catch (IOException e) {  
            e.printStackTrace();  
        }
        
        return "showFlowImage"; 
	}

	@RequestMapping(value = "/showFlowImageActive")
	public @ResponseBody String  showFlowImageActive(HttpServletRequest request,HttpServletResponse response, String taskId) throws Exception{
       response.setContentType("image/png");  
       response.setCharacterEncoding("utf-8");  
       try {  
             
           OutputStream outputStream=response.getOutputStream();  
           InputStream in = workFlowService.showFlowImage(taskId, "");  
           int len=0;  
           byte[]buf=new byte[1024];  
           while((len=in.read(buf,0,1024))!=-1){  
               outputStream.write(buf, 0, len);  
           }  
           outputStream.close();  
       } catch (IOException e) {  
           e.printStackTrace();  
       }  
       return "showFlowImage"; 
	}

}
